//除法函数，用来得到精确的除法结果
//说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
//调用：accDiv(arg1,arg2)
//返回值：arg1除以arg2的精确结果
function accDiv(arg1,arg2){
    var t1=0,t2=0,r1,r2;
    try{t1=arg1.toString().split(".")[1].length}catch(e){}
    try{t2=arg2.toString().split(".")[1].length}catch(e){}
    r1=Number(arg1.toString().replace(".",""));
    r2=Number(arg2.toString().replace(".",""));
    return (r1/r2)*Math.pow(10,t2-t1);
}
//给Number类型增加一个div方法，调用起来更加方便。
Number.prototype.div = function (arg){
    return accDiv(this, arg);
};
//乘法函数，用来得到精确的乘法结果
//说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
//调用：accMul(arg1,arg2)
//返回值：arg1乘以arg2的精确结果
function accMul(arg1,arg2)
{
    var m=0,s1=arg1.toString(),s2=arg2.toString();
    try{m+=s1.split(".")[1].length}catch(e){}
    try{m+=s2.split(".")[1].length}catch(e){}
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}
//给Number类型增加一个mul方法，调用起来更加方便。
Number.prototype.mul = function (arg){
    return accMul(arg, this);
};
//加法函数，用来得到精确的加法结果
//说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
//调用：accAdd(arg1,arg2)
//返回值：arg1加上arg2的精确结果
function accAdd(arg1,arg2){
    var r1,r2,m;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    return (arg1*m+arg2*m)/m;
}
//给Number类型增加一个add方法，调用起来更加方便。
Number.prototype.add = function (arg){
    return accAdd(arg,this);
}
//减法函数
function accSub(arg1,arg2){
    var r1,r2,m,n;
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
    m=Math.pow(10,Math.max(r1,r2));
    //last modify by deeka
    //动态控制精度长度
    n=(r1>=r2)?r1:r2;
    return ((arg2*m-arg1*m)/m).toFixed(n);
}
///给number类增加一个sub方法，调用起来更加方便
Number.prototype.sub = function (arg){
    return accSub(arg,this);
}

// Number.toFixed() 重写
Number.prototype.toFixed = function(d){
    var s=this+"";
    if(!d)d=0;
    if(s.indexOf(".")==-1)s+=".";
    s+=new Array(d+1).join("0");
    if(new RegExp("^(-|\\+)?(\\d+(\\.\\d{0,"+(d+1)+"})?)\\d*$").test(s)){
        var s="0"+RegExp.$2,pm=RegExp.$1,a=RegExp.$3.length,b=true;
        if(a==d+2){
            a=s.match(/\d/g);
            if(parseInt(a[a.length-1])>4){
                for(var i=a.length-2;i>=0;i--){
                    a[i]=parseInt(a[i])+1;
                    if(a[i]==10){
                        a[i]=0;
                        b=i!=1;
                    }else break;
                }
            }
            s=a.join("").replace(new RegExp("(\\d+)(\\d{"+d+"})\\d$"),"$1.$2");

        }if(b)s=s.substr(1);
        return (pm+s).replace(/\.$/,"");
    }return this+"";
}

export const formatDate = (date) => {
    if(!date) return '';
	 date = new Date(date);
    if (isNaN(date.getTime())) return '';
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();
	month = month < 10 ? ('0'+month):month;
	day = day < 10 ? ('0'+day):day;
    if(year + "-" + month +"-"+ day == EmptyDate || year + "-" + month +"-"+ day == EmptyDate2)
        return "";
	return year + "-" + month +"-"+ day;
}
//获取月份
export const formatMonth = (date) => {
    if (!date) return '';
    date = new Date(date);
    let year = date.getFullYear();
    let month = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`;
    return `${year}-${month}`;
}

export const getDepartMonths = (date1,date2) => {
    date1 = new Date(date1);
    if (isNaN(date1.getTime())) return -1;
    let year1 = date1.getFullYear();
    let month1 = date1.getMonth() + 1;

    date2 = new Date(date2);
    if (isNaN(date2.getTime())) return -1;
    let year2 = date2.getFullYear();
    let month2 = date2.getMonth() + 1;

    return Math.abs((year1*12+month1) - (year2*12+month2))+1;
}

export const createDateObjByTimeStr = (timeStr) => {
    if(!timeStr || timeStr.length == 0)
        return null;
    let date = new Date();
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = month < 10 ? ('0'+month):month;
    day = day < 10 ? ('0'+day):day;
    return new Date(year + "-" + month +"-" + day +" "+ timeStr);
}

export const getMonthFirstDate = (date) => {
    date = new Date(date);
    if (isNaN(date.getTime())) return '';
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = month < 10 ? ('0'+month):month;
    day = day < 10 ? ('0'+day):day;
    return year + "-" + month +"-01";
}

export const formatDateTime = (date) => {
    if(!date) return '';
	 date = new Date(date);
   if (isNaN(date.getTime())) return '';
	let year = date.getFullYear();
	let month = date.getMonth() + 1;
	let day = date.getDate();
	let hours = date.getHours();
	let minutes = date.getMinutes()
	month = month < 10 ? ('0'+month):month;
	day = day < 10 ? ('0'+day):day;
	hours = hours < 10 ? ('0'+hours):hours;
	minutes = minutes < 10 ? ('0'+minutes):minutes;
	return year + "-" + month +"-"+ day + " "+hours+":"+minutes;
}

export const formatTime = (date) => {
    if(!date) return '';
    date = new Date(date);
    if (isNaN(date.getTime())) return '';
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    month = month < 10 ? ('0'+month):month;
    day = day < 10 ? ('0'+day):day;
    hours = hours < 10 ? ('0'+hours):hours;
    minutes = minutes < 10 ? ('0'+minutes):minutes;
    seconds = seconds < 10 ? ('0'+seconds):seconds;
    if(year + "-" + month +"-"+ day == EmptyDate || year + "-" + month +"-"+ day == EmptyDate2)
        return "";
    return hours+":"+minutes+":"+seconds;
}

export const formatTimeNoSecond = (date) => {
    if(!date) return '';
    date = new Date(date);
    if (isNaN(date.getTime())) return '';
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    month = month < 10 ? ('0'+month):month;
    day = day < 10 ? ('0'+day):day;
    hours = hours < 10 ? ('0'+hours):hours;
    minutes = minutes < 10 ? ('0'+minutes):minutes;
    seconds = seconds < 10 ? ('0'+seconds):seconds;
    if(year + "-" + month +"-"+ day == EmptyDate || year + "-" + month +"-"+ day == EmptyDate2)
        return "";
    return hours+":"+minutes;
}

export const formatSeconds = (value) => {
 	let newValue = 0;
 	if(value<0){
 		newValue = -value;
 	}else{
 		newValue = value;
 	}
    let theTime = parseInt(newValue/1000);// 秒
    let theTime1 = 0;// 分
    let theTime2 = 0;// 小时
    let theDay = 0;	//天
    if(theTime > 0) {
        theTime1 = Math.ceil(theTime/60);
        // theTime = parseInt(theTime%60);
        if(theTime1 >= 60) {
	        theTime2 = parseInt(theTime1/60);
	        theTime1 = parseInt(theTime1%60);
        }
        if(theTime2>=24){
        	theDay = parseInt(theTime2/24);
        	theTime2 = parseInt(theTime2%24);
        }
    }
        var result = "";
        if(theTime1 > 0) {
            result = " "+parseInt(theTime1)+"min"+result;	//分钟
        }
        if(theTime2 > 0) {
        	result = " "+parseInt(theTime2)+"h"+result;  //小时
        }
        if(theDay >0 ){
        	result = " "+parseInt(theDay)+"d"+result; //天
        }
    return value<0 ? '-'+result : result;
}
/**
 * 计算当前时间和节点时间相距多少分钟
 * @param {*} cur 当前时间
 * @param {*} cul 节点时间
 */
export const leftMinutes = (cur, cul) => {
    if (cur && cul) {
        let curTimes = new Date(cur).getTime(),
            culTimes = new Date(cul).getTime(),
            minutesTime = curTimes - culTimes,
            minutes;
        minutes = Math.floor(minutesTime / (1000 * 60));

        return minutes;
    }
}

export const serializeFormat = (obj) => {
    var obj = {
        a:'111',
        b:[
            {
                b1:'222',
                b2:'333'
            },
            {
                b1:'222',
                b2:'333'
            }
        ],
        c:['11',22]
    }
    var data = '';
    for(var item in obj){
        console.log(typeof obj[item],obj[item]);
        if(typeof obj[item] == 'object'){
            for(var i = 0;i<obj[item].length;i++){
                if(typeof obj[item][i] == 'object'){
                    for(j in obj[item][i]){
                        if(data == ''){
                             data += j +'='+ obj[item][i][j];
                         }else{
                               data += '&'+j +'='+ obj[item][i][j];
                         }
                     
                    }
                }else{

                }
            }
        }else{
             if(data == ''){
                 data += item +'='+ obj[item];
             }else{
                   data += '&'+item +'='+ obj[item];
             }
        }  
    }
    console.log(data);
}

export const divScorllTop = (id) => {
    setTimeout(function(){
        let div = document.getElementById(id).parentNode;
        div.scrollTop = 0;
    },100);
    
}

window.Data={
    powerSet:{
        data:null
    }
}

export const initPowerSet = (urlArr) => {
    let urlSet = new Set();
    if(urlArr){
        urlArr.forEach(function(item){
            urlSet.add(item);
        });
    }
    return urlSet;
    //localStorage.ly_powerArr = JSON.stringify(urlArr);
}

export const hasPower = (urlSet,url) => {//urlSet,
    //let urlArr = [];
    //if(localStorage.ly_powerArr)
    //{
    //    urlArr = JSON.parse(localStorage.ly_powerArr);
    //}
    //
    //let urlSet = new Set();
    //urlArr.forEach(function(item){
    //    urlSet.add(item);
    //});


    let newUrl = url.toUpperCase();
    if(urlSet && urlSet.has(newUrl))
    {
        return true;
    }
    return false;
}

export const obj2Form = (obj) => {
    var parts=[];
    for(var k in obj){
        if (obj.hasOwnProperty(k)) {
            var val = obj[k];
            if (Array.isArray(val)) {
                for (var i = 0; i < val.length; i++) {
                    if (val[i] || val[i] === 0 || val[i] === '0') {
                        parts.push(k + "=" + val[i]);
                    }
                }
            } else {
                if (val || val === 0 || val === '0') {
                    parts.push(k + "=" + val);
                }
            }
        }
    }
    return  parts.join("&") ? "?" + encodeURI(parts.join("&")) : "";
}

export const EmptyDate = '1753-01-01';
export const EmptyDate2 = '1900-01-01';

export const getDateNoTime = (date) => {
    date = new Date(date);
    if (isNaN(date.getTime())) return null;
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    month = month < 10 ? ('0'+month):month;
    day = day < 10 ? ('0'+day):day;
    return new Date(year + "-" + month +"-"+ day);
}

export const needDisableDate = (typeStr,currentDate,compareDate) => {
    if(!typeStr || (typeStr != "forStart" && typeStr != "forEnd")) return false;
    let result = false;
    if(typeStr == "forStart" && compareDate && getDateNoTime(currentDate) > getDateNoTime(compareDate)){
        result = true;
    }
    else if(typeStr == "forEnd" && compareDate && getDateNoTime(currentDate) < getDateNoTime(compareDate)){
        result = true;
    }
    return result;
}

//去左右空格;
export const trim = (s) =>{
    return s.replace(/(^\s*)|(\s*$)/g, "");
}

//计算两个日期的间隔天数
export const GetDateDiff  = (startDate,endDate) => {
    var startTime = new Date(Date.parse(startDate.replace(/-/g,   "/"))).getTime();
    var endTime = new Date(Date.parse(endDate.replace(/-/g,   "/"))).getTime();
    var dates = Math.abs((startTime - endTime))/(1000*60*60*24) + 1;
    return  dates;
}


/**********************复制到剪切板开始*********************/
var deselectCurrent = function () {
    var selection = document.getSelection();
    if (!selection.rangeCount) {
        return function () {};
    }
    var active = document.activeElement;

    var ranges = [];
    for (var i = 0; i < selection.rangeCount; i++) {
        ranges.push(selection.getRangeAt(i));
    }

    switch (active.tagName.toUpperCase()) { // .toUpperCase handles XHTML
        case 'INPUT':
        case 'TEXTAREA':
            active.blur();
            break;

        default:
            active = null;
            break;
    }

    selection.removeAllRanges();
    return function () {
        selection.type === 'Caret' &&
        selection.removeAllRanges();

        if (!selection.rangeCount) {
            ranges.forEach(function(range) {
                selection.addRange(range);
            });
        }

        active &&
        active.focus();
    };
};

export const copy  = function (text,callback ,options) {
    var debug, copyKey, message, cb, reselectPrevious, range, selection, mark;
    if (!options) { options = {}; }
    debug = options.debug || false;
    copyKey = /mac os x/i.test(navigator.userAgent) ? '⌘' : 'Ctrl';
    message = options.message || 'Copy to clipboard: ' + copyKey + '+C, Enter';
    cb = options.cb || Function.prototype;
    try {
        reselectPrevious = deselectCurrent();

        range = document.createRange();
        selection = document.getSelection();

        mark = document.createElement('mark');
        mark.textContent = text;
        // used to conserve newline, etc
        mark.style.whiteSpace = 'pre';
        document.body.appendChild(mark);

        range.selectNode(mark);
        selection.addRange(range);

        var successful = document.execCommand('copy');
        if (!successful) {
            throw new Error('copy command was unsuccessful');
        }else{
            //alert("链接地址已经复制！");
            if(callback)
            {
                callback();
            }
        }
    } catch (err) {
        debug && console.error('unable to copy, trying IE specific stuff');
        try {
            window.clipboardData.setData('text', text);
        } catch (err) {
            debug && console.error('unable to copy, falling back to prompt');
            window.prompt(message, text);

        }
    } finally {
        cb(null);
        if (selection) {
            if (typeof selection.removeRange == 'function') {
                selection.removeRange(range);
            } else {
                selection.removeAllRanges();
            }
        }

        if (mark) {
            document.body.removeChild(mark);
        }
        reselectPrevious();
    }
}

/**********************复制到剪切板结束*********************/


//去掉默认时间
export const filterEmptyTime = (timeText)=>{
    if(!timeText){
        return "";
    }
    let result = timeText;
    if(timeText.indexOf("1900-01-01") > -1)
    {
        result = "-";
    }
    else if(timeText.indexOf("0001-01-01") > -1)
    {
        result = "-";
    }
    return result;
}


// 获取系统用户信息
export const getUserSystemInfo = ()=> {
    let Info = localStorage.getItem('MEN-DIAN-UINFO')
    if (Info && Info !== '{}') {
        Info = JSON.parse(Info)
    }
    return Info
}

//此函数只在本地执行时才会调用，本地执行时cookie中无值用于写入测试数据
function setCookie(c_name, c_value, expiredays) {
    let exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + '=' + c_value + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}
//获取cookie中信息
function getCookie(c_name) {
    if(document.cookie.length > 0) {
        let c_start = document.cookie.indexOf(c_name + '='),
            c_end;
        if(c_start != -1){
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if(c_end == -1) {
                c_end = document.cookie.length;
            }
            return JSON.parse(document.cookie.substring(c_start, c_end)); 
        }else {
            return '';
        }
    } else {
        return '';
    }
}

//从cookie中获取系统用户信息
export const getSystemUserInfo = ()=> {
    // setCookie('user_info', '{"stationid":0,"name":"仝腾","jobNumber":"49125","stationType":0}', 1);
    // setCookie('test', '{"stationid":0,"name":"仝腾","jobNumber":"49125","stationType":0}', 1);
    let user_info = getCookie('user_info');
    return user_info;
}

/**
 * @description 过滤对象不必要的字段
 * @param obj 类型object 需要过滤的对象
 * @param filterCondition （类型array）  过滤条件， 例如传 [null, '']， 过滤掉所有等于null 和 ''
 * @return newObj 返回一个新的对象
 */
export const filterObj = (obj, filterCondition) => {
  let value;
  let sign;
  let newObj = {};
  for(let key in obj){
    value = obj[key];
    sign = 1;
    for(let i=0; i<filterCondition.length; i++) {
      if(value === filterCondition[i]) {
        sign = 0;
        break;
      }
    }
    if(sign){
      newObj[key] = value ;
    }
  }
  return newObj;
}
